package com.yimi.policyservice.controller;
import cn.hutool.crypto.SecureUtil;
import com.yimi.policyservice.common.annotation.Auth;
import com.yimi.policyservice.common.constant.MsgConstant;
import com.yimi.policyservice.common.constant.RedisConstant;
import com.yimi.policyservice.common.expetion.ApiException;
import com.yimi.policyservice.dto.code.ImageCode;
import com.yimi.policyservice.dto.code.SmsCode4Send;
import com.yimi.policyservice.entity.base.system.SysUser;
import com.yimi.policyservice.service.ImgCodeService;
import com.yimi.policyservice.service.SmsCodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 验证码
 * @author jack
 */
@RestController
@RequestMapping("code")
public class CodeController extends  BaseController {


    @Autowired
    private ImgCodeService imgCodeService ;

    @Autowired
    private SmsCodeService smsCodeService ;



    /**
     * 图片验证码
     * 10分钟有效
     * @return
     */
    @RequestMapping(value = "/img",method = RequestMethod.GET)
    public ImageCode picCode(){
        return  imgCodeService.create();
    }

    /**
     * 发送短信验证码
     * @param bean
     */
    @RequestMapping(value = "sms",method = RequestMethod.POST)
    public void sendSmsCode(@RequestBody SmsCode4Send bean){
        boolean  img=  imgCodeService.verify(bean.getImgKey(),bean.getImgCode());
        if(!img){
            throw  new ApiException(400,MsgConstant.IMG_CODE_ERROR);
        }
        smsCodeService.send(bean.getPhone(),402699);
    }


    /**
     * 发送绑定手机短信验证码
     */
    @RequestMapping(value = "sms2",method = RequestMethod.POST)
    @Auth
    public void sendSmsCodeForBindPhone(@RequestParam String phone, @RequestParam String password){
        SysUser sysUser = getLoginUser();
        String md5passwoed = SecureUtil.md5(password);
        if(!StringUtils.equals(md5passwoed,sysUser.getPassword())){
            throw  new ApiException(400,"请输入正确的密码");
        }
        String code = smsCodeService.code(phone);
        if(StringUtils.isBlank(code)){
            smsCodeService.send(phone,410282);
        }
    }






}
